<?php 

namespace App\Admin\Controllers;

include base_path() . '/vendor/autoload.php';
use EasyWeChat\Foundation\Application;
use DB;
use Validator;
use Session;
use Auth;
use Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use App\WxPublicUser;
use App\WxMessage;

class ServerController extends Controller
{

	protected $config = [
	    'app_id' => 'wx555be570d21859aa',
	    'secret' => 'f92678be7687d1e1b1471ca9c066f242',
	    'token' => 'leyougame2018'
	];

	public function generateButton()
	{
		$app = new Application($this->config);
        // $result = $app->material->uploadImage("/home/www/leyougame/public/image/iphone.png");
        // dd($result);
		$buttons = [
		    [
		        "type" => "view",
		        "name" => "🎁乐游游乐场",
		        "url" => "http://wx.hortor.net/gc?channel=lysy"
		    ],
            [
                "name" => "乐游棋牌",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "游戏下载",
                        // "url" => "http://fir.im/91z4"
                        "url" => "http://user.leyougame.cc/mobile/download_game"
                    ],
                    [
                        "type" => "click",
                        "name" => "苹果如何安装",
                        // "url" => "http://user.leyougame.cc/mobile/iphone"
                        "key" => "IOS_INSTALL"
                    ],
                    [
                        "type" => "view",
                        "name" => "免费银票",
                        "url" => "http://user.leyougame.cc/mobile/everyday_ticket"
                    ],
                    // [
                    //     "type" => "click",
                    //     "name" => "官方活动",
                    //     "key" => "NEW_ACTIVE"
                    // ],
                    [
                        "type" => "view",
                        "name" => "抽奖活动",
                        "url" => "http://user.leyougame.cc/mobile/draw_lottery"
                    ],
                ]    
            ],        
            [
                "name" => "合作推广",
                "sub_button" => [
                    // [
                    //     "type" => "view",
                    //     "name" => "申请推广合作",
                    //     "url" => "http://user.leyougame.cc/mobile/index"
                    // ],
                    [
                        "type" => "view",
                        "name" => "推广后台",
                        "url" => "http://user.leyougame.cc/mobile/agent_login"
                    ],
                    // [
                    //     "type" => "click",
                    //     "name" => "推广手册",
                    //     "key" => "PUSH_MANUAL_V001"
                    // ]
                ],
            ]
		];
		$app->menu->add($buttons);
	}

	public function index()
	{
		if (!isset($_GET['echostr'])) {
		    $this->responseMsg();
		}else{
		    $this->valid();
		}
	}

    //验证签名
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = 'leyougame2018';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            echo $echoStr;
            exit;
        }
        $siteURL='http://47.95.202.91/server';
    }

    public function responseMsg()
    {
        $postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $openid = $postObj->FromUserName;
            if ($openid) {
            	$exist = WxPublicUser::where(['openid' => $openid])->first();
            	if (!$exist) {
            		$exist = new WxPublicUser;
            		$exist->openid = $openid;
                    $exist->save();
                    $is_new = 1;
            	} else {
                    $exist->updated_at = date('Y-m-d H:i:s', time());
                    $exist->save();
            	}
            }
            $RX_TYPE = trim($postObj->MsgType);
            $result = "";
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
            }
            
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

    private function receiveText($object)
    {
        $keyword = trim($object->Content);
        $context = WxMessage::where(['keywords' => $keyword])->first();
        if ($context) {
        	$content = base64_decode($context->content);
        } else {
        	$content = "您好!欢迎来到乐游手游!";
        }
        $result = $this->transmitText($object, $content);
        
        return $result;
    }

    private function transmitText($object, $content)
    {
        if (!isset($content) || empty($content)){
            return "";
        }
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    private function transmitImg($object, $content)
    {
        if (!isset($content) || empty($content)){
            return "";
        }
        $imgTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[image]]></MsgType>
                    <Image>
                    <MediaId><![CDATA[%s]]></MediaId>
                    </Image>
                    </xml>";
        $result = sprintf($imgTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        Log::info('--------xml--------');
        Log::info($result);
        return $result;            
    }

    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return "";
        }
        $itemTpl = "    <item>
                            <Title><![CDATA[%s]]></Title>
                            <Description><![CDATA[%s]]></Description>
                            <PicUrl><![CDATA[%s]]></PicUrl>
                            <Url><![CDATA[%s]]></Url>
                        </item>
                    ";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $newsTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <Content><![CDATA[]]></Content>
                    <ArticleCount>%s</ArticleCount>
                    <Articles>
                    $item_str</Articles>
                    </xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }
    

    private function logger($log_content)
    {
      
    }

    private function receiveEvent($object)
    {
        switch ($object->Event)
        {
            case "subscribe":
                Log::info('-----------------'.$object->EventKey);
                if (strpos($object->EventKey, 'qrscene_qrscene') !== false) {
                    $agent_id = substr(strstr($object->EventKey, "qrscene_qrscene"), strlen("qrscene_qrscene"));//代理id
                    $array = [
                        [
                            'Title' => '乐游在手，欢乐无忧!',
                            'Description' => '点我下载游戏',
                            'PicUrl' => 'http://user.leyougame.cc/image/yxxc.png',
                            'Url' => 'http://user.leyougame.cc/mobile/download?aid='.$agent_id
                        ]
                    ];
                    $result = $this->transmitNews($object, $array);
                    return $result;
                } elseif (strpos($object->EventKey, 'superagent_') !== false) {
                    $agent_id = substr(strstr($object->EventKey, "superagent_"), strlen("superagent_"));//代理id
                    $content = "欢迎关注乐游棋牌，<a href='http://user.leyougame.cc/mobile/index?aid=$agent_id'>👉注册成为代理👈</a>";
                } else {
                   $array = [
                        [
                            'Title' => '乐游在手，欢乐无忧!',
                            'Description' => '点我下载游戏',
                            'PicUrl' => 'http://user.leyougame.cc/image/yxxc.png',
                            'Url' => 'http://user.leyougame.cc/mobile/download_game'
                        ]
                    ];
                    $result = $this->transmitNews($object, $array);
                    return $result;
                }
                break;
            case "SCAN":
                Log::info('-----------------'.$object->EventKey);
                if (strpos($object->EventKey, 'qrscene') !== false) {
                    $agent_id = substr(strstr($object->EventKey, "qrscene"), strlen("qrscene"));//代理id
                    $array = [
                        [
                            'Title' => '乐游在手，欢乐无忧!',
                            'Description' => '点我下载游戏',
                            'PicUrl' => 'http://user.leyougame.cc/image/yxxc.png',
                            'Url' => 'http://user.leyougame.cc/mobile/download?aid='.$agent_id
                        ]
                    ];
                    $result = $this->transmitNews($object, $array);
                    return $result;
                } elseif (strpos($object->EventKey, 'superagent_') !== false) {
                    $agent_id = substr(strstr($object->EventKey, "superagent_"), strlen("superagent_"));//代理id
                    $content = "欢迎关注乐游棋牌，<a href='http://user.leyougame.cc/mobile/index?aid=$agent_id'>👉注册成为代理👈</a>";
                } else {
                   $content = "欢迎关注乐游棋牌!";
                }
                break;
            case "CLICK":
                if ($object->EventKey == "PUSH_MANUAL_V001") {
                    $array = [
                        [
                            'Title' => '乐游棋牌推广员明细',
                            'Description' => '',
                            'PicUrl' => 'http://user.leyougame.cc/image/first_push.png',
                            'Url' => ''
                        ],
                        [
                            'Title' => '乐游棋牌一级推广员说明',
                            'Description' => '',
                            'PicUrl' => 'http://user.leyougame.cc/image/first_push.png',
                            'Url' => 'http://user.leyougame.cc/mobile/first_push_explain'
                        ],
                        [
                            'Title' => '乐游棋牌二级推广员说明',
                            'Description' => '',
                            'PicUrl' => 'http://user.leyougame.cc/image/second_push.png',
                            'Url' => 'http://user.leyougame.cc/mobile/second_push_explain'
                        ]
                    ];
                    $result = $this->transmitNews($object, $array);
                    return $result;
                } else if ($object->EventKey == "NEW_ACTIVE") {
                    $array = [
                        [
                            'Title' => '最新活动',
                            'Description' => '百万现金红包等你来赢!',
                            'PicUrl' => 'http://user.leyougame.cc/image/newactive.png',
                            'Url' => 'http://user.leyougame.cc/mobile/new_active'
                        ],
                        [
                            'Title' => '世界杯冠军竞猜',
                            'Description' => '',
                            'PicUrl' => 'http://user.leyougame.cc/image/wc_champion.jpg',
                            'Url' => 'http://user.leyougame.cc/mobile/worldcup/champion'
                        ],
                        [
                            'Title' => '世界杯每日竞猜',
                            'Description' => '',
                            'PicUrl' => 'http://user.leyougame.cc/image/wc_dayguess.jpg',
                            'Url' => 'http://user.leyougame.cc/mobile/worldcup/day_guess'
                        ]
                    ];
                    $result = $this->transmitNews($object, $array);
                    return $result;
                } else if ($object->EventKey == "IOS_INSTALL") {
                    Log::info("iosinstall------------------------------------");
                    $result = $this->transmitImg($object, "o587d1ESz_Mh8CM59bm3OzgPJIhRlBSmSF2-GXtCtm0");
                    return $result;
                } else {
                    $content = "欢迎关注乐游棋牌!";
                }
                break;
            default :
                $content = "欢迎关注乐游棋牌!!";
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }


}	